<template>
    <el-dialog v-model="printVisible" :show-close="false" @open="openPrintProductionEvent" fullscreen>
        <!-- 标题 -->
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">产品生产单 --- ESC关闭</h4>
                <el-button type="danger" @click="close">
                    <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
                    关闭
                </el-button>
            </div>
        </template>
        <!-- 打印内容 -->
        <div v-if="productData.length > 0" class="print-content">
            <!-- 固定按钮 -->
            <el-affix :offset="50">
                <el-button v-if="printBtnSymbol" plain @click="print('ImgAndTable')">双面打印(含图稿)</el-button>
                <el-button v-if="printBtnSymbol" plain @click="print('OnlyTable')">单面打印(仅表单)</el-button>
            </el-affix>
            <!-- 打印生产单内容 -->
            <div id="print-production-container">
                <!-- 遍历所有产品信息 -->
                <div v-for="(item, index) in productData" :key="index" class="print-production">
                    <img
                        ref="imgEl"
                        :src="item.design[0] && item.design[0].thumbnail !== '' ? item.design[0].thumbnail : ''"
                        class="print-production-thumbnail"
                    />
                    <!-- 抬头 -->
                    <h2>生产单</h2>
                    <!-- 标题 -->
                    <h3>
                        <span>制单人：{{ useUserStore().username }}</span>
                        <span>客户：{{ matchCustomerInfo(matchOrderSomeInfo(item._id)?.customerId as string)?.customerName }}</span>
                        <span>制单时间：{{ dayjs().format('YYYY-MM-DD HH:mm:ss') }}</span>
                    </h3>
                    <!-- 表单 -->
                    <table>
                        <tbody>
                            <tr>
                                <td>
                                    <div>
                                        产品名称：{{ item.productName }}
                                        <br />
                                        包装类型：{{ item.boxType }}
                                    </div>
                                </td>
                                <td>产品尺寸：{{ item.productSize }}</td>
                            </tr>
                            <tr>
                                <td>面纸规格：{{ item.tissueSize }}</td>
                                <td>瓦楞规格：{{ item.corrugatedSize }}</td>
                            </tr>
                            <tr>
                                <td>材质：{{ item.materialQuality }}</td>
                                <td>压线：{{ item.crimping }}</td>
                            </tr>
                            <tr>
                                <td>拼数：{{ item.spell }}</td>
                                <td>
                                    工艺：{{ item.process }}
                                    <br />
                                    描述：{{ item.description }}
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    订单数量：{{ matchOrderSomeInfo(item._id)?.orderNumber }}
                                    <br />
                                    采购数量：{{ matchOrderSomeInfo(item._id)?.purchaseNumber }}
                                </td>
                                <td>
                                    生产数量：
                                    <br />
                                    送货日期：{{
                                        matchOrderSomeInfo(item._id)?.orderDeliveryDate == '暂无送货计划'
                                            ? '暂无送货计划'
                                            : formatTimeZone(matchOrderSomeInfo(item._id)?.orderDeliveryDate as Date, 'YYYY-MM-DD')
                                    }}
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2" class="remarks">
                                    <span>备注：{{ item.remarks }}</span>
                                    <br />
                                    <textarea class="print-production-remark"></textarea>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2" class="print-production-operator">
                                    <span>操作工批注：</span>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <!-- 没有打印内容 -->
        <div v-if="productData.length === 0" class="w-full flex items-center justify-center">
            <el-empty description="没有查询到对应的产品，请重新下订单后再次打印生产单。" />
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import { getProductInfo } from '@/api/product';
import { useUserStore } from '@/store/modules/user';
import { CircleCloseFilled } from '@element-plus/icons-vue';
import { getCustomerList } from '@/api/customer';
import { updateOrderPrintFlag } from '@/api/purchase';
import { formatTimeZone } from '@utils/calculate';
import printJS from 'print-js';
import dayjs from 'dayjs';

/* ******************************暴露给父组件的属性/方法****************************** */
// 打印生产单dialog开关
const printVisible = defineModel('printVisible', { type: Boolean, required: true });
// 打印按钮的标识
const printBtnSymbol = defineModel('printBtnSymbol', { type: Boolean, required: true });
// 需要打印的订单数据
const printData = defineModel('printData', {
    type: Array<{
        orderId: string;
        customerId: string;
        productId: string;
        orderNumber: number;
        purchaseNumber: number;
        orderDeliveryDate: Date | string;
    }>,
    required: true,
});

/* ******************************通用属性/方法****************************** */
// 产品数据
const productData = reactive<AjaxResponse['productList']>([]);
// 客户数据
const customerData = reactive<AjaxResponse['customerList']>([]);

// 打开dialog加载产品完整数据
const openPrintProductionEvent = async () => {
    // 清空数据
    productData.length = 0;
    customerData.length = 0;
    // 获取数据
    for (let index = 0; index < printData.value.length; index++) {
        const item = printData.value[index];
        const result = await getProductInfo(item.customerId, item.productId);
        productData.push(result.data);
    }
    // 获取客户信息
    const result = await getCustomerList(true);
    customerData.push(...result.data);
};
// 获取订单的部分信息
const matchOrderSomeInfo = (id: string) => {
    return printData.value.find((item) => item.productId === id);
};
// 获取客户的信息
const matchCustomerInfo = (id: string) => {
    return customerData.find((item) => item._id === id);
};

/* ******************************打印属性/方法****************************** */
// 预览图片的url
const imgEl = ref();
// 调用print-js打印
const print = (type: 'OnlyTable' | 'ImgAndTable') => {
    // 单面打印表单
    if (type == 'OnlyTable') {
        // 移除图片
        imgEl.value.forEach((item) => item.remove());
    }
    // 调用系统打印机
    printJS({
        printable: 'print-production-container',
        type: 'html',
        scanStyles: false,
        style: `
            .print-production {
                display: flex;
                flex-wrap: wrap;
                justify-content: center;
                align-items: center;
            }
            .print-production-thumbnail {
                width: 100%;
                height: 700px;
            }
            .print-production-remark {
                margin-top: 2px;
                height: 6rem;
                width: 95%;
                border: solid 1px black;
            }
            .print-production-operator {
                vertical-align: top;
                height: 6rem;
            }
            h2 {
                width: 100%;
                font-size: 1.5rem;
                text-align: center;
            }
            h3 {
                width: 100%;
                display: flex;
                font-size: 1.2rem;
                justify-content: space-around;
                margin-bottom: 20px;
            }
            table {
                width: 100%;
                text-align: center;
            }

            table,
            th,
            td {
                border: 1px solid #333;
                border-collapse: collapse;
            }

            td {
                padding: 0 0 0 5px;
                height: 4.2rem;
                text-align: left;
            }
        `,
    });
    // 更新数据库相关内容 -- 订单打印状态
    const orderId: string[] = [];
    printData.value.map((item) => orderId.push(item.orderId));
    updateOrderPrintFlag(orderId).then(() => {
        ElMessage({
            type: 'success',
            message: '订单打印状态更新成功。',
            grouping: true,
        });
        printVisible.value = false;
    });
};

// 监听打印事件
</script>

<style scoped lang="scss">
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}

.print-production {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
}
.print-production-thumbnail {
    width: 100%;
    height: 700px;
}
.print-production-remark {
    margin-top: 2px;
    height: 6rem;
    width: 95%;
    border: solid 1px black;
}
.print-production-operator {
    vertical-align: top;
    height: 6rem;
}
h2 {
    width: 100%;
    font-size: 1.5rem;
    text-align: center;
}
h3 {
    width: 100%;
    display: flex;
    font-size: 1.2rem;
    justify-content: space-around;
    margin-bottom: 20px;
}
table {
    width: 100%;
    text-align: center;
}

table,
th,
td {
    border: 1px solid #333;
    border-collapse: collapse;
}

td {
    padding: 0 0 0 5px;
    height: 4.2rem;
    text-align: left;
}
</style>
